#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

SSH安全检测模块

包含SSH相关的安全检测功能：
- SSH服务状态检测
- SSH密钥后门条件检测
- SSH软链接后门条件检测
- SSH用户后门条件检测
"""

import os
from core.utils import SystemInfo, ml, color, color_red, color_green, color_yellow, color_title
from core.distro_detection import detect_linux_distro





# 创建系统信息实例
system_info = SystemInfo()


def check_ssh_service_status(distro=None):
    """
    统一的SSH服务状态检测函数
    
    Args:
        distro: Linux发行版类型，如果为None则自动检测
        
    Returns:
        bool: SSH服务是否运行中
    """
    try:
        if distro is None:
            distro = detect_linux_distro()
        
        ssh_service_commands = []
        
        if distro == 'debian_based':
            ssh_service_commands = [
                'systemctl is-active ssh 2>/dev/null',
                'systemctl is-active sshd 2>/dev/null', 
                'service ssh status 2>/dev/null',
                'service sshd status 2>/dev/null'
            ]
        elif distro == 'fedora_based':
            ssh_service_commands = [
                'systemctl is-active sshd 2>/dev/null',
                'systemctl is-active ssh 2>/dev/null',
                'systemctl status sshd 2>/dev/null | grep -i active',
                'service sshd status 2>/dev/null'
            ]
        elif distro == 'alpine_based':
            ssh_service_commands = [
                'rc-service sshd status 2>/dev/null',
                'rc-service ssh status 2>/dev/null',
                'rc-status | grep sshd 2>/dev/null',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        elif distro == 'alibaba_based':
            ssh_service_commands = [
                'systemctl is-active sshd 2>/dev/null',
                'systemctl is-active ssh 2>/dev/null',
                'systemctl status sshd 2>/dev/null | grep -i active',
                'service sshd status 2>/dev/null',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        elif distro == 'anolis_based':
            ssh_service_commands = [
                'systemctl is-active sshd 2>/dev/null',
                'systemctl is-active ssh 2>/dev/null',
                'systemctl status sshd 2>/dev/null | grep -i active',
                'service sshd status 2>/dev/null',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        elif distro == 'centos_based':
            ssh_service_commands = [
                'systemctl is-active sshd 2>/dev/null',
                'systemctl is-active ssh 2>/dev/null',
                'systemctl status sshd 2>/dev/null | grep -i active',
                'service sshd status 2>/dev/null',
                'chkconfig --list sshd 2>/dev/null',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        elif distro == 'centos_stream_based':
            ssh_service_commands = [
                'systemctl is-active sshd 2>/dev/null',
                'systemctl is-active ssh 2>/dev/null',
                'systemctl status sshd 2>/dev/null | grep -i active',
                'service sshd status 2>/dev/null',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        elif distro == 'rhel_based':
            ssh_service_commands = [
                'systemctl is-active sshd 2>/dev/null',
                'systemctl is-active ssh 2>/dev/null',
                'systemctl status sshd 2>/dev/null | grep -i active',
                'service sshd status 2>/dev/null',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        elif distro == 'suse_based':
            ssh_service_commands = [
                'systemctl is-active sshd 2>/dev/null',
                'systemctl is-active ssh 2>/dev/null',
                'systemctl status sshd 2>/dev/null | grep -i active',
                'service sshd status 2>/dev/null',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        elif distro == 'arch_based':
            ssh_service_commands = [
                'systemctl is-active sshd 2>/dev/null',
                'systemctl is-active ssh 2>/dev/null',
                'systemctl status sshd 2>/dev/null | grep -i active',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        elif distro == 'gentoo_based':
            ssh_service_commands = [
                'rc-service sshd status 2>/dev/null',
                'rc-service ssh status 2>/dev/null',
                '/etc/init.d/sshd status 2>/dev/null',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        else:
            # 通用命令
            ssh_service_commands = [
                'systemctl is-active sshd 2>/dev/null',
                'systemctl is-active ssh 2>/dev/null',
                'service sshd status 2>/dev/null',
                'service ssh status 2>/dev/null',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        
        # 尝试执行命令检查SSH服务状态
        for cmd in ssh_service_commands:
            try:
                output = ml(cmd).strip()
                if output:
                    # 检查输出是否表示服务正在运行
                    if ('active' in output.lower() or 
                        'running' in output.lower() or 
                        'started' in output.lower() or
                        'sshd' in output.lower()):
                        return True
            except:
                continue
        
        return False
        
    except Exception:
        return False


def check_sshkey():
    """
    检查SSH密钥后门条件
    
    检测系统中SSH密钥后门存在的条件，包括：
    1. 当前用户的authorized_keys文件存在性
    2. 其他用户的authorized_keys文件存在性（需要root权限）
    3. sshd_config文件的写权限检查
    
    Returns:
        None
        
    Condition Checks:
        - 检查SSH授权密钥文件是否存在
        - 检查sshd配置文件权限条件
        - 统计SSH密钥数量条件
        
    Output:
        打印SSH密钥后门存在的条件信息
    """
    color_title("SSH密钥后门条件检测")
    
    try:
        current_user = system_info.get_current_user()
        conditions_met = []
        
        # 条件1: 检查当前用户的authorized_keys文件是否存在
        user_ssh_dir = "/home/{}/.ssh".format(current_user)
        if system_info.is_root_user():
            user_ssh_dir = "/root/.ssh"
        
        authorized_keys_path = "{}/authorized_keys".format(user_ssh_dir)
        
        if os.path.exists(authorized_keys_path):
            try:
                with open(authorized_keys_path, 'r') as f:
                    keys_content = f.read().strip()
                    if keys_content:
                        key_lines = [line for line in keys_content.split('\n') if line.strip() and not line.strip().startswith('#')]
                        if key_lines:
                            conditions_met.append("条件满足: 当前用户存在 {} 个SSH密钥文件".format(len(key_lines)))
                            color("✓ 发现SSH密钥文件: {} (包含 {} 个密钥)".format(authorized_keys_path, len(key_lines)))
                        else:
                            # 文件有内容但都是注释或空行
                            color_yellow("? SSH密钥文件存在但仅包含注释: {}".format(authorized_keys_path))
                    else:
                        # 空文件可能表示：1) 正常清理 2) 被恶意清空 3) 准备植入后门
                        file_stat = os.stat(authorized_keys_path)
                        file_size = file_stat.st_size
                        file_mode = oct(file_stat.st_mode)[-3:]
                        
                        color_yellow("? SSH密钥文件存在但为空: {}".format(authorized_keys_path))
                        color("  文件大小: {} 字节, 权限: {}".format(file_size, file_mode))
                        
                        # 检查文件权限是否异常
                        if file_mode not in ['600', '644']:
                            conditions_met.append("条件满足: 空SSH密钥文件权限异常")
                            color_red("  警告: 空SSH密钥文件权限异常 ({})".format(file_mode))
                        
                        # 检查是否可写（可能被用于植入后门）
                        if os.access(authorized_keys_path, os.W_OK):
                            color_yellow("  注意: 空SSH密钥文件可写，存在被植入后门的风险")
            except Exception as e:
                color_red("无法读取SSH密钥文件: {} - {}".format(authorized_keys_path, e))
        else:
            color("○ 当前用户无SSH密钥文件: {}".format(authorized_keys_path))
        
        # 条件2: 检查其他用户的authorized_keys文件（需要root权限）
        if system_info.is_root_user():
            try:
                users_output = ml('cat /etc/passwd | cut -d: -f1,6')
                other_users_with_keys = 0
                for line in users_output.split('\n'):
                    if ':' in line:
                        username, home_dir = line.strip().split(':', 1)
                        if username != current_user and home_dir.startswith('/'):
                            other_auth_keys = "{}/.ssh/authorized_keys".format(home_dir)
                            if os.path.exists(other_auth_keys):
                                try:
                                    with open(other_auth_keys, 'r') as f:
                                        keys_content = f.read().strip()
                                        if keys_content:
                                            key_lines = [line for line in keys_content.split('\n') if line.strip() and not line.strip().startswith('#')]
                                            if key_lines:
                                                other_users_with_keys += 1
                                                color("✓ 用户 {} 存在SSH密钥文件 (包含 {} 个密钥)".format(username, len(key_lines)))
                                            else:
                                                color_yellow("? 用户 {} SSH密钥文件仅包含注释: {}".format(username, other_auth_keys))
                                        else:
                                            # 其他用户的空SSH密钥文件也需要关注
                                            file_stat = os.stat(other_auth_keys)
                                            file_mode = oct(file_stat.st_mode)[-3:]
                                            color_yellow("? 用户 {} SSH密钥文件为空: {} (权限: {})".format(username, other_auth_keys, file_mode))
                                            
                                            # 检查权限是否异常
                                            if file_mode not in ['600', '644']:
                                                color_red("  警告: 用户 {} 空SSH密钥文件权限异常 ({})".format(username, file_mode))
                                except Exception as e:
                                    color_red("无法读取用户 {} 的SSH密钥文件: {}".format(username, e))
                
                if other_users_with_keys > 0:
                    conditions_met.append("条件满足: {} 个其他用户存在SSH密钥文件".format(other_users_with_keys))
                else:
                    color("○ 其他用户均无SSH密钥文件")
                    
            except Exception as e:
                color_red("检查其他用户SSH密钥文件失败: {}".format(e))
        else:
            color("○ 非root用户，无法检查其他用户的SSH密钥文件")
        
        # 条件3: 检查sshd_config写权限条件
        sshd_config_paths = ["/etc/ssh/sshd_config", "/etc/sshd_config"]
        sshd_config_found = False
        
        for sshd_config_path in sshd_config_paths:
            if os.path.exists(sshd_config_path):
                sshd_config_found = True
                try:
                    # 检查文件权限
                    stat_info = os.stat(sshd_config_path)
                    file_mode = oct(stat_info.st_mode)[-3:]
                    
                    # 检查权限是否异常（正常应该是600或644）
                    if file_mode in ['600', '644']:
                        # 正常权限，但检查是否为非root用户但有写权限（在Linux环境下）
                        try:
                            current_uid = os.getuid() if hasattr(os, 'getuid') else -1
                            if os.access(sshd_config_path, os.W_OK) and current_uid != 0 and current_uid != -1:
                                conditions_met.append("条件满足: 非root用户对sshd_config有写权限")
                                color_red("! 非root用户对sshd_config有写权限 ({}, 权限: {})".format(sshd_config_path, file_mode))
                            else:
                                color_green("○ sshd_config文件权限正常 ({}, 权限: {})".format(sshd_config_path, file_mode))
                        except:
                            # 其他异常情况
                            color_green("○ sshd_config文件权限正常 ({}, 权限: {})".format(sshd_config_path, file_mode))
                    elif file_mode in ['666', '777', '646', '647', '676', '677']:
                        # 异常权限 - 过于宽松
                        conditions_met.append("条件满足: sshd_config文件权限过于宽松")
                        color_red("! sshd_config文件权限过于宽松 ({}, 权限: {})".format(sshd_config_path, file_mode))
                    elif '2' in file_mode or '3' in file_mode:
                        # 包含写权限位
                        conditions_met.append("条件满足: sshd_config文件权限异常")
                        color_yellow("? sshd_config文件权限异常 ({}, 权限: {})".format(sshd_config_path, file_mode))
                    else:
                        color_green("○ sshd_config文件权限正常 ({}, 权限: {})".format(sshd_config_path, file_mode))
                except Exception as e:
                    color_red("检查sshd_config权限失败: {} - {}".format(sshd_config_path, e))
                break
        
        if not sshd_config_found:
            color("○ sshd_config文件不存在")
        
        # 条件4: 检查SSH服务是否运行（针对CentOS优化）
        try:
            distro = detect_linux_distro()
            ssh_service_running = False
            
            if distro in ['centos_based', 'centos_stream_based']:
                # CentOS/CentOS Stream特有的SSH服务检测
                ssh_commands = [
                    'systemctl is-active sshd 2>/dev/null',
                    'service sshd status 2>/dev/null | grep -i running',
                    'ps aux | grep sshd | grep -v grep',
                    'netstat -tlnp | grep :22'
                ]
                
                for cmd in ssh_commands:
                    try:
                        result = ml(cmd)
                        if result.strip():
                            if 'active' in result.lower() or 'running' in result.lower() or 'sshd' in result.lower() or ':22' in result:
                                ssh_service_running = True
                                break
                    except:
                        continue
            else:
                # 使用通用检测方法
                ssh_service_running = check_ssh_service_status()
            
            if ssh_service_running:
                # SSH服务运行是正常的，但需要检查是否有异常配置
                try:
                    # 检查SSH配置是否有异常端口
                    sshd_config_content = ""
                    for config_path in ["/etc/ssh/sshd_config", "/etc/sshd_config"]:
                        if os.path.exists(config_path):
                            with open(config_path, 'r') as f:
                                sshd_config_content = f.read().lower()
                            break
                    
                    # 检查是否有异常配置
                    suspicious_configs = []
                    if 'permitrootlogin yes' in sshd_config_content:
                        suspicious_configs.append("允许root登录")
                    if 'passwordauthentication no' not in sshd_config_content and 'pubkeyauthentication yes' in sshd_config_content:
                        suspicious_configs.append("仅允许密钥认证但密码认证未明确禁用")
                    if 'port 22' not in sshd_config_content and 'port' in sshd_config_content:
                        suspicious_configs.append("使用非标准SSH端口")
                    
                    if suspicious_configs:
                        conditions_met.append("条件满足: SSH服务配置存在安全风险")
                        color_yellow("? SSH服务运行但配置可疑: {}".format(', '.join(suspicious_configs)))
                    else:
                        color_green("○ SSH服务正常运行，配置安全")
                        
                except Exception as e:
                    # 如果无法读取配置，仅报告服务状态
                    color_green("○ SSH服务正常运行")
            else:
                color("○ SSH服务未运行")
                
        except Exception as e:
            color_red("SSH服务状态检测失败: {}".format(e))
            # 备用检测方法
            try:
                result = ml('ps aux | grep sshd | grep -v grep')
                if result.strip():
                    conditions_met.append("条件满足: SSH服务正在运行")
                    color("? SSH服务正在运行 (通过进程检测)")
                else:
                    color("○ SSH服务未运行")
            except:
                color("○ 无法检测SSH服务状态")
        
        # 总结条件检测结果
        color_title("SSH密钥后门条件总结")
        
        # 显示检测环境信息
        try:
            distro = detect_linux_distro()
            distro_names = {
                'debian_based': 'Debian/Ubuntu系统',
                'centos_based': 'CentOS系统',
                'centos_stream_based': 'CentOS Stream系统',
                'rhel_based': 'RHEL系列系统(Rocky/AlmaLinux/RHEL)',
                'fedora_based': 'Fedora系统',
                'suse_based': 'SUSE系列系统(openSUSE/SLES)',
                'arch_based': 'Arch Linux系列系统(Arch/Manjaro)',
                'alpine_based': 'Alpine Linux系统',
                'gentoo_based': 'Gentoo系统',
                'alibaba_based': 'Alibaba Cloud Linux系统',
                'anolis_based': 'Anolis OS系统'
            }
            distro_name = distro_names.get(distro, distro)
            color("检测环境: {}".format(distro_name))
        except:
            pass
        
        if conditions_met:
            color("满足 {} 个SSH密钥后门条件:".format(len(conditions_met)))
            for condition in conditions_met:
                color("  • {}".format(condition))
        else:
            color("未满足SSH密钥后门的基本条件")
            
    except Exception as e:
        color_red("SSH密钥后门条件检测失败: {}".format(e))


def check_ssh_user_backdoor():
    """
    检查SSH后门用户条件
    
    检测系统中SSH后门用户存在的条件，包括：
    1. 检查是否具有创建用户的权限
    2. 检查用户管理工具的可用性
    3. 检查/etc/passwd文件的可写性
    4. 检查sudo权限
    
    Returns:
        None
        
    Condition Checks:
        - 检查用户创建权限
        - 检查用户管理工具可用性
        - 检查关键文件权限
        
    Output:
        打印SSH后门用户存在的条件信息
    """
    color_title("SSH后门用户条件检测")
    
    try:
        conditions_met = []
        
        # 条件1: 检查当前用户权限
        try:
            current_user = system_info.get_current_user()
            if system_info.is_root_user():
                conditions_met.append("条件满足: 当前用户为root")
                color("✓ 当前用户为root")
            else:
                color("○ 当前用户为: {} (非root)".format(current_user))
        except Exception:
            color("○ 无法检测当前用户")
        
        # 条件2: 检查用户管理工具的可用性
        user_tools = ['useradd', 'adduser', 'usermod', 'passwd']
        available_tools = []
        for tool in user_tools:
            try:
                tool_check = ml('which {}'.format(tool))
                if tool_check.strip():
                    available_tools.append(tool)
            except Exception:
                pass
        
        if available_tools:
            conditions_met.append("条件满足: 系统中存在 {} 个用户管理工具".format(len(available_tools)))
            color("✓ 可用用户管理工具: {}".format(', '.join(available_tools)))
        else:
            color("○ 系统中无用户管理工具")
        
        # 条件3: 检查/etc/passwd文件的可写性
        if os.path.exists('/etc/passwd'):
            if os.access('/etc/passwd', os.W_OK):
                conditions_met.append("条件满足: /etc/passwd文件具有写权限")
                color("✓ /etc/passwd文件具有写权限")
            else:
                color("○ /etc/passwd文件无写权限")
        else:
            color("○ /etc/passwd文件不存在")
        
        # 条件4: 检查sudo权限
        try:
            # 如果当前用户是root，则直接认为具有最高权限
            current_user = system_info.get_current_user()
            if current_user == 'root' or (hasattr(os, 'getuid') and os.getuid() == 0):
                conditions_met.append("条件满足: 当前用户为root，具有最高权限")
                color("✓ 当前用户为root，具有最高权限")
            else:
                # 对于非root用户，检查sudo权限
                sudo_check = ml('sudo -l')
                if sudo_check and 'not allowed' not in sudo_check.lower():
                    conditions_met.append("条件满足: 当前用户具有sudo权限")
                    color("✓ 当前用户具有sudo权限")
                else:
                    color("○ 当前用户无sudo权限")
        except Exception:
            color("○ 无法检测sudo权限")
        
        # 总结条件检测结果
        color_title("SSH后门用户条件总结")
        if conditions_met:
            color("满足 {} 个SSH后门用户条件:".format(len(conditions_met)))
            for condition in conditions_met:
                color("  • {}".format(condition))
        else:
            color("未满足SSH后门用户的基本条件")
            
    except Exception as e:
        color_red("SSH后门用户条件检测失败: {}".format(e))


def check_ssh_soft_link_backdoor():
    """检查SSH软链接后门条件"""
    color_title("SSH软链接后门条件检测")
    
    try:
        conditions_met = []
        
        # 条件1: 检测当前用户权限
        try:
            current_user = ml('whoami').strip()
            if current_user == 'root':
                conditions_met.append("条件满足: 当前用户为root")
                color("✓ 当前用户为root")
            else:
                color("○ 当前用户为: {} (非root)".format(current_user))
        except Exception:
            color("○ 无法检测当前用户")
        
        # 条件2: 检测SSH服务状态
        try:
            ssh_service_running = check_ssh_service_status()
            
            if ssh_service_running:
                conditions_met.append("条件满足: SSH服务运行中")
                color("✓ SSH服务运行中")
            else:
                color("○ SSH服务未运行")
        except Exception:
            color("○ 无法检测SSH服务状态")
        
        # 条件3: 检测PAM配置状态
        try:
            sshd_config = ml('cat /etc/ssh/sshd_config 2>/dev/null')
            use_pam_line = [line.strip() for line in sshd_config.split('\n') if line.strip().startswith('UsePAM')]
            
            if not use_pam_line:
                # 无显式配置，默认启用PAM
                conditions_met.append("条件满足: PAM认证启用 (默认)")
                color("✓ PAM认证启用 (默认配置)")
            else:
                # 有显式配置
                use_pam_enabled = (use_pam_line[0].split()[-1].lower() == 'yes')
                if use_pam_enabled:
                    conditions_met.append("条件满足: PAM认证启用 (显式配置)")
                    color("✓ PAM认证启用 (显式配置)")
                else:
                    color("○ PAM认证未启用")
        except Exception:
            color("○ 无法检测PAM配置")
        
        # 条件4: 检测关键文件的软链接状态
        check_paths = [
            '/etc/pam.d/sshd',
            '/usr/sbin/sshd',
            '/usr/bin/sshd'
        ]
        
        soft_links_found = []
        for path in check_paths:
            try:
                if ml('[ -L {} ] && echo "is_link" 2>/dev/null'.format(path)).strip() == 'is_link':
                    link_target = ml('readlink -f {} 2>/dev/null'.format(path)).strip()
                    soft_links_found.append("{} -> {}".format(path, link_target))
                    color("✓ 发现软链接: {} -> {}".format(path, link_target))
                else:
                    color("○ 非软链接: {}".format(path))
            except Exception:
                color("○ 无法检测: {}".format(path))
        
        if soft_links_found:
            conditions_met.append("条件满足: 发现 {} 个软链接".format(len(soft_links_found)))
        
        # 条件5: 检测PAM模块目录的可写性
        try:
            pam_dirs = ['/lib/security', '/lib64/security', '/usr/lib/security', '/usr/lib64/security']
            writable_pam_dirs = []
            
            for pam_dir in pam_dirs:
                if os.path.exists(pam_dir) and os.access(pam_dir, os.W_OK):
                    writable_pam_dirs.append(pam_dir)
            
            if writable_pam_dirs:
                conditions_met.append("条件满足: {} 个PAM目录可写".format(len(writable_pam_dirs)))
                color("✓ 可写PAM目录: {}".format(', '.join(writable_pam_dirs[:2])))  # 只显示前2个
            else:
                color("○ PAM目录均不可写")
        except Exception:
            color("○ 无法检测PAM目录权限")
        
        # 条件6: 检测SSH配置文件的可写性
        try:
            ssh_config_files = ['/etc/ssh/sshd_config', '/etc/pam.d/sshd']
            writable_configs = []
            
            for config_file in ssh_config_files:
                if os.path.exists(config_file) and os.access(config_file, os.W_OK):
                    writable_configs.append(config_file)
            
            if writable_configs:
                conditions_met.append("条件满足: {} 个SSH配置文件可写".format(len(writable_configs)))
                color("✓ 可写SSH配置: {}".format(', '.join(writable_configs)))
            else:
                color("○ SSH配置文件均不可写")
        except Exception:
            color("○ 无法检测SSH配置文件权限")
        
        # 总结条件检测结果
        color_title("SSH软链接后门条件总结")
        if conditions_met:
            color("满足 {} 个SSH软链接后门条件:".format(len(conditions_met)))
            for condition in conditions_met:
                color("  • {}".format(condition))
        else:
            color("未满足SSH软链接后门的基本条件")
            
    except Exception as e:
        color_red("SSH软链接后门条件检测失败: {}".format(e))


def check_ssh_Soft_link():
    """检查SSH软链接后门条件（备用函数）"""
    color_title("SSH软链接后门条件检测")
    
    try:
        conditions_met = []
        
        # 条件1: 检查当前用户权限
        try:
            current_user = ml('whoami').strip()
            if current_user == 'root':
                conditions_met.append("条件满足: 当前用户为root")
                color("✓ 当前用户为root")
            else:
                color("○ 当前用户为: {} (非root)".format(current_user))
        except Exception:
            color("○ 无法检测当前用户")
        
        # 条件2: 检查SSH配置文件可访问性
        try:
            sshd_config = ml('cat /etc/ssh/sshd_config 2>/dev/null')
            if sshd_config.strip():
                conditions_met.append("条件满足: SSH配置文件可访问")
                color("✓ SSH配置文件可访问")
            else:
                color("○ SSH配置文件不可访问")
        except Exception:
            color("○ 无法访问SSH配置文件")
        
        # 条件3: 检查UsePAM配置状态
        try:
            sshd_config = ml('cat /etc/ssh/sshd_config 2>/dev/null')
            use_pam_enabled = False
            use_pam_explicitly_set = False
            
            for line in sshd_config.split('\n'):
                line = line.strip()
                if line.startswith('UsePAM'):
                    use_pam_explicitly_set = True
                    if 'yes' in line.lower():
                        use_pam_enabled = True
                    break
            
            # 如果没有显式设置UsePAM，检查系统类型确定默认值
            if not use_pam_explicitly_set:
                distro_type = detect_linux_distro()
                # RHEL/CentOS/Rocky Linux默认UsePAM=yes
                if distro_type == 'rhel_based':
                    use_pam_enabled = True
            
            if use_pam_enabled:
                if use_pam_explicitly_set:
                    conditions_met.append("条件满足: UsePAM显式启用")
                    color("✓ UsePAM显式启用")
                else:
                    conditions_met.append("条件满足: UsePAM默认启用")
                    color("✓ UsePAM默认启用")
            else:
                color("○ UsePAM未启用")
        except Exception:
            color("○ 无法检测UsePAM配置")
        
        # 条件4: 检查PAM模块存在性
        try:
            pam_modules = ml('ls /lib*/security/pam_*.so 2>/dev/null | head -5')
            if pam_modules.strip():
                conditions_met.append("条件满足: PAM模块存在")
                color("✓ PAM模块存在")
                # 显示部分模块（限制输出）
                modules = pam_modules.strip().split('\n')[:3]
                for module in modules:
                    color("  模块: {}".format(module))
            else:
                color("○ 未发现PAM模块")
        except Exception:
            color("○ 无法检测PAM模块")
        
        # 条件5: 检查系统类型兼容性
        try:
            distro_type = detect_linux_distro()
            if distro_type in ['rhel_based', 'debian_based']:
                conditions_met.append("条件满足: 系统类型兼容 ({})".format(distro_type))
                color("✓ 系统类型兼容: {}".format(distro_type))
            else:
                color("○ 系统类型: {}".format(distro_type))
        except Exception:
            color("○ 无法检测系统类型")
        
        # 条件6: 检查SSH服务运行状态
        try:
            ssh_service_running = check_ssh_service_status()
            
            if ssh_service_running:
                conditions_met.append("条件满足: SSH服务运行中")
                color("✓ SSH服务运行中")
            else:
                color("○ SSH服务未运行")
        except Exception:
            color("○ 无法检测SSH服务状态")
        
        # 总结条件检测结果
        color_title("SSH软链接后门条件总结")
        if conditions_met:
            color("满足 {} 个SSH软链接后门条件:".format(len(conditions_met)))
            for condition in conditions_met:
                color("  • {}".format(condition))
        else:
            color("未满足SSH软链接后门的基本条件")
            
    except Exception as e:
        color_red("SSH软链接后门条件检测失败: {}".format(e))


# 为兼容性添加别名
check_ssh_soft_link_backdoor = check_ssh_Soft_link